package com.example.shushiyunsst.fragment.main.transaction.child.content

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.transaction.bean.AllDelegateBean
import com.example.shushiyunsst.fragment.main.transaction.bean.ContentListBean
import com.example.shushiyunsst.fragment.main.transaction.child.TRANSFER_DECIMAL_FORMAT
import com.example.shushiyunsst.fragment.main.transaction.child.transfer_index
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import ikidou.reflect.TypeBuilder
import org.greenrobot.eventbus.EventBus
import java.lang.reflect.Type
import java.text.DecimalFormat

/**
 * 全部委托
 * */
class AllDelegateFragment : SimpleListFragment<AllDelegateBean>(), OnItemChildClickListener {

    companion object {
        fun newInstance(): AllDelegateFragment {
            val args = Bundle()

            val fragment = AllDelegateFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val df = DecimalFormat(TRANSFER_DECIMAL_FORMAT)

    private val sstStr = AppGlobals.getApplication().getString(R.string.wallet_sst)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isAddDividerItemDecoration = false
    }


    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()
        addHeader(R.layout.comment_header_layout)
        mHeader.setBackgroundResource(R.color.bg_color_0)
        val mToolbar: Toolbar = mHeader.findViewById(R.id.mToolbar)
        mToolbar.title = "全部"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        mAdapter.addChildClickViewIds(R.id.cancel_deal)
        mAdapter.setOnItemChildClickListener(this)
    }

    override fun getItemLayout(): Int {
        return R.layout.all_delegate_fragment
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: AllDelegateBean?) {
        val transactionTypeStr = if (item?.txType == 1) "买" else "卖"
        val transactionTypeColor =
            if (item?.txType == 1) R.color.PrimaryColor else R.color.image_color_red
        val statusDesc = when (item?.txStatus) {
            0 -> "交易撤销"
            1 -> "交易进行中"
            2 -> "交易完成"
            else -> ""
        }
        helper?.setText(R.id.transactionTypeTv, transactionTypeStr)
            ?.setViewVisible(R.id.cancel_deal, item?.txStatus == 1)
            ?.setTextColorRes(R.id.transactionTypeTv, transactionTypeColor)
            ?.setText(R.id.statusDesc, statusDesc)
            ?.setText(R.id.transactionTimeTv, "${item?.createTime}")
            ?.setText(R.id.transactionPriceTitleTv, "价格（${sstStr})")
            ?.setText(R.id.transactionCountTitleTv, "数量（${item?.tokenType})")
            ?.setText(R.id.actuallyDealTitleTv, "实际成交（${item?.tokenType})")
            ?.setText(R.id.transactionPriceTv, df.format(item?.txPrice))
            ?.setText(R.id.transactionCountTv, df.format(item?.txNums))
            ?.setText(R.id.actuallyDealTv, df.format(item?.txNumsDeal))
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(AllDelegateBean::class.java).endSubType().build()
    }

    override fun netRequest() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "pageCount" to 30,
            "pageIndex" to pageIndex,
            "uid" to "${userInfo?.uid}",
//            "uid" to "126",
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryMyTransTxList)
            .success {
                parseDate(it)
            }
            .failure { onFailed() }
            .error { _, _ -> onFailed() }
            .build().post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val list = obj["list"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(list), AllDelegateBean::class.java)
        loadListDate(array)

    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.cancel_deal -> {
                cancelDeal(item)
            }
        }
    }

    private fun cancelDeal(item: AllDelegateBean?) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo


        val map = mapOf(
            "txId" to "${item?.txId}",
            "uid" to "${userInfo?.uid}"
        )

        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.cancelTransTxList)
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_LONG).show()
                if (!mSwipeRefreshLayout.isRefreshing) {
                    mSwipeRefreshLayout.isRefreshing = true
                }
                onRefresh()

                EventBus.getDefault().post(MessageWrap.getInstance(transfer_index))
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }
}